/*
 * @Description: 描述信息
 * @Version: 版本号
 * @Author: xuebao
 * @Date: 2023-12-12 14:06:47
 * @LastEditors: xuebao
 * @LastEditTime: 2023-12-14 21:34:27
 */
import { Button, Table, Form, Input, Select, Space, Modal } from 'antd'
import type { ColumnsType } from 'antd/es/table'
import { PageParams, User } from '@/types/api'
import { useEffect, useRef, useState } from 'react'
import api from '@/api'
import CreateUser from './CreateUser'
import { formatDate } from '@/utils'
import { IAction } from '@/types/modal'
import { message } from '@/utils/AntdGlobal'
import { useAntdTable } from 'ahooks'
import AuthButton from '@/components/AuthButton'
import SearchForm from '@/components/SearchForm'
export default function UserList() {
  const userRef = useRef<{
    open: (type: IAction, data?: User.UserItem) => void
  }>()
  const [form] = Form.useForm()
  const [userIds, setUserIds] = useState<number[]>([])

  //删除用户
  const handleDel = (userId: number) => {
    // delUser
    Modal.confirm({
      title: '删除用户',
      content: '确定删除该用户吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => handleUserSubmit([userId]),
    })
  }
  const getTableData = ({ current, pageSize }: { current: number; pageSize: number }, formData: User.SearchParams) => {
    return api
      .getUserList({
        ...formData,
        pageNum: current,
        pageSize,
      })
      .then((data) => {
        return {
          total: data.page.total,
          list: data.list,
        }
      })
  }

  const { tableProps, search } = useAntdTable(getTableData, {
    form, //参数的表单值传禁区
    defaultPageSize: 10,
  })
  //公共删除用户接口
  const handleUserSubmit = async (ids: number[]) => {
    try {
      await api.delUser({
        userIds: ids,
      })
      message.success('删除成功')
      setUserIds([])
      search.reset()
    } catch (error) {}
  }
  //编辑用户
  const handleEdit = (record: User.UserItem) => {
    userRef.current?.open('edit', record)
  }
  const columns: ColumnsType<User.UserItem> = [
    {
      title: '用户ID',
      dataIndex: 'userId',
      key: 'userId',
    },
    {
      title: '用户名称',
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '用户邮箱',
      dataIndex: 'userEmail',
      key: 'userEmail',
    },
    {
      title: '用户角色',
      dataIndex: 'role',
      key: 'role',
      render(role: number) {
        return {
          0: '超级管理员',
          1: '管理员',
          2: '体验管理员',
          3: '普通用户',
        }[role]
      },
    },
    {
      title: '用户状态',
      dataIndex: 'state',
      key: 'state',
      render(state: number) {
        return {
          1: '在职',
          2: '离职',
          3: '试用期',
        }[state]
      },
    },
    {
      title: '注册时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render(createTime: string) {
        return formatDate(createTime)
      },
    },

    {
      title: '操作',
      key: 'address',
      render(val, record: User.UserItem) {
        return (
          <Space>
            <Button type='text' onClick={() => handleEdit(record)}>
              编辑
            </Button>
            <Button type='text' danger onClick={() => handleDel(record.userId)}>
              删除
            </Button>
          </Space>
        )
      },
    },
  ]

  //创建用户
  const handleCreate = () => {
    userRef.current?.open('create')
  }
  //批量删除
  const handlePatchConfirm = () => {
    if (userIds.length === 0) {
      message.error('请选择要删除的用户')
      return
    }
    Modal.confirm({
      title: '删除确认',
      content: '确定删除选中用户吗？',
      onOk: () => {
        handleUserSubmit(userIds)
      },
    })
  }
  return (
    <div className='user-list'>
      <SearchForm form={form} initialValues={{ state: 1 }} submit={search.submit} reset={search.reset}>
        <Form.Item name='userId' label='用户ID'>
          <Input placeholder='请输入用户id'></Input>
        </Form.Item>
        <Form.Item name='userName' label='用户名称'>
          <Input placeholder='请输入用户名成'></Input>
        </Form.Item>
        <Form.Item name='state' label='状态'>
          <Select style={{ width: 120 }}>
            <Select.Option value={0}>所有</Select.Option>
            <Select.Option value={1}>在职</Select.Option>
            <Select.Option value={2}>离职</Select.Option>
            <Select.Option value={3}>试用期</Select.Option>
          </Select>
        </Form.Item>
      </SearchForm>

      <div className='base-table'>
        <div className='header-wrapper'>
          <div className='title'>用户列表</div>
          <div className='action'>
            {/* auth代表权限内容，必须符合 */}
            {/* <AuthButton auth='create' type='primary' onClick={handleCreate}>
              新增
            </AuthButton> */}
            <AuthButton type='primary' onClick={handleCreate}>
              新增
            </AuthButton>
            <Button type='primary' danger onClick={handlePatchConfirm}>
              批量删除
            </Button>
          </div>
        </div>
        <Table
          bordered
          {...tableProps}
          rowSelection={{
            type: 'checkbox',
            selectedRowKeys: userIds,
            onChange: (selectedRowKeys: React.Key[]) => {
              setUserIds(selectedRowKeys as number[])
            },
          }}
          rowKey='userId'
          columns={columns}
        />
      </div>
      <CreateUser mRef={userRef} update={() => search.reset()} />
    </div>
  )
}
